package com.netty.web.controller;

import com.netty.utils.GuavaCacheUtil;
import com.netty.utils.R;
import com.netty.web.utils.VerifyCode;
import com.netty.web.vo.RequestEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;

/**
 * @author zl
 * @version 1.0
 * @date 2021/10/27 10:38
 */
@Api(tags = "登录操作")
@RestController
@RequestMapping("/")
public class LoginController {
    @Autowired
    private TUserController tUserController;

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public R login(@Validated @RequestBody RequestEntity.login login){
        try{
            if(!Objects.equals(login.getCode().toLowerCase(), GuavaCacheUtil.getIfPresent(login.getUuid()))){
                throw new Exception("验证码输入错误,请重新输入!");
            }
            GuavaCacheUtil.remove(login.getUuid());
            R r = tUserController.queryUser(login.getEmail(), login.getPassword());
            if(Objects.equals(r.get("code"),0)){
                return r;
            }
            return r;
        }catch (Exception e){
            return R.error(e.getMessage());
        }
    }
    @ApiOperation("获取验证码")
    @GetMapping("/verifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
        try {
            String uuid = request.getParameter("uuid");
            VerifyCode vc = new VerifyCode();
            BufferedImage bi = vc.getImage(); // 生成图片
            GuavaCacheUtil.put(uuid,vc.getText().toLowerCase());
            VerifyCode.output(bi, response.getOutputStream());// 把图片响应给客户端
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
